#pragma once 

#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <mutex>
#include <cassert>
#include <jsoncpp/json/json.h>
#include <algorithm>

#include "../comm/log.hpp"
#include "../comm/util.hpp"
#include "./oj_model2.hpp"
#include "./oj_view.hpp"

const std::string server_machine = "./conf/server_machine.conf";


namespace ns_control
{
    using namespace ns_model;
    using namespace ns_view;
    using namespace ns_util;
    using namespace ns_logUtil;
    using namespace httplib;

    class Machine
        {
        public:
            std::string ip;
            int port;
            uint64_t load;
            std::mutex *mtx;
        public:
            Machine(): ip(""), port(0), load(0), mtx(nullptr)
            {}

            ~Machine()
            {}

        public:
            // 提升主机负载
            void IncLoad()
            {
                if(mtx) mtx->lock();
                ++load;
                if(mtx) mtx->unlock();
            }

            void ResetLoad()
            {
                if(mtx) mtx->lock();
                load = 0;
                if(mtx) mtx->unlock();
            }
            // 减少主机负载
            void DecLoad()
            {
                if(mtx) mtx->lock();
                --load;
                if(mtx) mtx->unlock();
            }

            uint64_t Load()
            {
                uint64_t _load = 0;
                if(mtx) mtx->lock();
                _load = load;
                if(mtx) mtx->unlock();

                return _load;
            }
        };

        class LoadBalance
        {
        private:
            std::vector<Machine> machines;
            // 所有在线的主机id
            std::vector<int> online;
            // 所有离线的主机id
            std::vector<int> offline;

            std::mutex mtx;
        
       public:
            LoadBalance()
            {
                assert(LoadConf(server_machine));
            } 
            ~LoadBalance()
            {} 

        public:
            bool LoadConf(const std::string &machine_conf)
            {
                std::ifstream in(machine_conf);
                if(!in.is_open())
                {
                    LOG(FATAL) << " 加载: " << machine_conf << " 失败"<<std::endl;
                    return false;
                }
                
                std::string line;
                while(std::getline(in, line))
                {
                    std::vector<std::string> tokens;
                    StringUtil::SplitString(line, tokens, ":");
                    if(tokens.size() != 2)
                    {
                        LOG(WARNING) << " 切分" <<  line << " 失败"<< std::endl;
                        continue;
                    }
                    Machine m;
                    m.ip = tokens[0];
                    m.port = atoi(tokens[1].c_str());
                    m.load = 0;
                    m.mtx = new std::mutex();

                    // // Debug 
                    // std::cout << m.ip << ":"<<m.port << std::endl;
                    online.push_back(machines.size());
                    machines.push_back(m);
                }

                in.close();
                return true;
            }

            bool SmartChoice(int *id, Machine **m)
            {
                // 1. 选择好的主机（负载最小的)并且更新该主机的负载
                // 2. 我们可能需要离线该主机
                mtx.lock();

                int online_num = online.size();
                if(online_num == 0)
                {
                    mtx.unlock();
                    LOG(FATAL) << "所有主机已经离线....." << std::endl;
                    return false;
                }

                // 通过遍历，找到负载最小的机器
                *id = online[0];
                *m = &machines[online[0]];
                uint64_t min_load = machines[online[0]].Load();
                for(int i = 1; i < online_num; i++)
                {
                    uint64_t cur_load = machines[online[i]].Load();
                    if(min_load > cur_load)
                    {
                        min_load = cur_load;
                        *id = online[i];
                        *m = &machines[online[i]];
                    }
                }
                 
                LOG(INFO) << "SmartChoice Success!" << std::endl;
                mtx.unlock(); 
                return true;
            }

            void OfflineMachine(int id)
            {
                mtx.lock();
                for(auto iter = online.begin(); iter != online.end(); iter++)
                {
                    if(*iter == id)
                    {
                        machines[id].ResetLoad();
                        online.erase(iter);
                        offline.push_back(id);
                        break;
                    }
                }

                mtx.unlock();
            }

            // 所有主机全部上线
            void OnlineMachines()
            {
                mtx.lock();
                online.insert(online.end(), offline.begin(), offline.end());
                offline.erase(offline.begin(), offline.end());
                mtx.unlock();

                LOG(INFO) << "所有主机全部上线啦！" << std::endl;
            }

            void ShowMachines()
            {
                mtx.lock();
                std::cout << "当前主机列表： ";
                for(auto &id : online)
                {
                    std::cout << id << " ";
                }
                std::cout << std::endl;
                std::cout << "当前离线主机列表： ";
                for(auto &id : offline)
                {
                    std::cout<<id<<" ";
                }
                std::cout << std::endl;
                mtx.unlock();
            }
        };

    class Control
    {
    private:
        Model _model;
        View _view;
        LoadBalance _load_balance;
    public:
        Control()
        {}
        ~Control()
        {}

    public:
        void RecoveryMachine()
        {
            _load_balance.OnlineMachines();
        }

        // 获取经过渲染后的全部题目的html
        bool AllQuestions(std::string *html)
        {
            // //Debug
            // std::cout << "渲染点1"<<std::endl;
            bool ret = true;
            std::vector<struct Question> all;

            if(_model.GetAllQuestions(&all))
            {
                // 获取全部题目成功
                sort(all.begin(), all.end(), [](const struct Question &q1, const struct Question &q2){
                    return atoi(q1.number.c_str()) < atoi(q2.number.c_str());
                });
                _view.AllExpandHtml(all, html); // 进行页面渲染
                LOG(INFO)<<"题目列表的页面渲染成功！"<<std::endl;
            }
            else
            {
                // 获取全部题目失败
                *html = "获取全部题目失败";
                ret = false;
                LOG(FATAL)<<"题目列表的页面渲染失败！"<<std::endl;
            }

            return ret;
        }

        bool OneQuestion(const std::string &number, std::string *html)
        {
            bool ret = true;
            Question q;
            if(_model.GetOneQuestions(number, &q))
            {
                // 获取指定题目成功
                _view.OneExpandHtml(q, html);
            }
            else
            {
                // 获取指定题目失败
                (*html) = "获取编号为：" + number +"的题目失败！！";
                ret = false;
            }

            return ret;
        }

        void Judge(const std::string &number, const std::string in_json, std::string *out_json)
        {
            struct Question q;
            _model.GetOneQuestions(number, &q);

            Json::Reader reader;
            Json::Value in_value;
            reader.parse(in_json, in_value);
            std::string code = in_value["code"].asString();

            Json::Value compile_value;
            compile_value["input"] = in_value["input"].asString();
            compile_value["code"] = code + "\n" + q.tail;
            compile_value["cpu_limit"] = q.cpu_limit;
            compile_value["mem_limit"] = q.mem_limit;
            Json::FastWriter writer;
            std::string compile_string = writer.write(compile_value);

            // 循环选则， 直到出现负载最低且可用的主机
            while(true)
            {
                int id = 0;
                Machine *m = nullptr;
                if(!_load_balance.SmartChoice(&id, &m))
                {
                    break;
                }
                // // Debug 
                //     std::cout <<"dd:  "<< m->ip << ":"<<m->port << std::endl;
                // 已经选择了最佳的主机
                Client cli(m->ip, m->port);
                m->IncLoad();
                LOG(INFO)<<" 选择主机成功，主机id： " << id << " 详情： " << m->ip << ":"<<m->port<<" 当前主机的负载是："<< m->Load() << std::endl;
                if(auto res = cli.Post("/compile_and_run", compile_string, "application/json;charset=utf-8"))
                {
                    if(res->status == 200)
                    {
                        *out_json = res->body;
                        m->DecLoad();
                        LOG(INFO)<<"请求编译和运行成功..." << std::endl;
                        break;
                    }
                    m->DecLoad();
                }
                else
                {   
                    // 请求失败
                    LOG(ERROR) << " 当前请求的主机id: "<< id << " 详情："<<m->ip<<":"<<m->port<<std::endl;
                    _load_balance.OfflineMachine(id);

                    //测试：
                    _load_balance.ShowMachines();
                }
            }
        }
    };
}